#include "knxenvagent.h"
#include <QUdpSocket>

#define MIN_PORT_NUM  1025
#define MAX_PORT_NUM  65535

quint16 KnxEnvAgent::freePort = MIN_PORT_NUM;

KnxEnvAgent::KnxEnvAgent(QObject *parent) :
    QObject(parent)
{

}


KnxEnvAgent * KnxEnvAgent::getSingleObj()
{
    static KnxEnvAgent * single;
    if(!single)
        single = new KnxEnvAgent();
    return single;
}

quint16 KnxEnvAgent::getCurrentPortNum(){
    return freePort;
}

void KnxEnvAgent::searchPort(quint16 *port)
{
    QUdpSocket udp;
    int fail_time = 0;
    while(true)
    {
        if(freePort>= MAX_PORT_NUM)
            freePort = MIN_PORT_NUM;

        if(udp.bind(QHostAddress::Any,freePort,QUdpSocket::ShareAddress))
        {            
            udp.close();
            *port = freePort++;
            return ;
        }
        else
        {
            freePort++;
            fail_time ++;
        }

        if(fail_time > 2*MAX_PORT_NUM)
        {
            *port = -1;
            return ;
        }
    }
}

bool KnxEnvAgent::getFreePort(quint16 *portCnt,quint16 *portData)
{
    KnxEnvAgent::searchPort(portCnt);
    KnxEnvAgent::searchPort(portData);

    if(*portCnt==-1 || *portData==-1)
        return false;
    else
        return true;
}
